package com.iRomantic.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class ShortUrlUtil {
	/**
	 * 创建短网址url
	 */
	private static final String SERVICE_CREATE = "http://dwz.cn/create.php";
	
	/**
	 * 查询短网址原始值
	 */
	private static final String SERVICE_QUERY = "http://dwz.cn/query.php";
	
	/**
	 * 初始化httpclient客户端
	 * @return
	 */
	private DefaultHttpClient createHttpClient() {
		HttpParams httpParameters = new BasicHttpParams();
		HttpClientParams.setCookiePolicy(httpParameters,CookiePolicy.BROWSER_COMPATIBILITY);
		HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
		HttpConnectionParams.setSoTimeout(httpParameters, 16000);
		DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
		return httpclient;
	}
	
	/**
	 * 创建短网址服务
	 * @param url
	 * @return
	 * @throws Exception 
	 */
	public String createShortUrl(String url){
		JSONObject json = invokeRemateCreateService(SERVICE_CREATE,"url",url);
		if("0".equals(json.getString("status"))){
			//成功
			return json.getString("tinyurl");
		}else{
			//失败
			return null;
		}
	}
	
	/**
	 * 查询短网址的原始值
	 * @param url
	 * @return
	 */
	public String queryByShortUrl(String url){
		JSONObject json = invokeRemateCreateService(SERVICE_QUERY,"tinyurl",url);
		if("0".equals(json.getString("status"))){
			//成功
			return json.getString("longurl");
		}else{
			//失败
			return null;
		}
	}
	
	/**
	 * 分析返回的响应报文
	 * @param response
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	private HttpResponse parseRespnose(HttpClient client,HttpResponse response) throws ClientProtocolException, IOException{
		int statusCode = response.getStatusLine().getStatusCode();
		if(statusCode==302 || statusCode==301){//跳转
			String url = response.getFirstHeader("Location").getValue();
			response.getEntity().consumeContent();
			HttpPost post = new HttpPost(url);
			HttpResponse resp = client.execute(post);
			post.abort();
			return parseRespnose(client,resp);
			
		}else if(statusCode==200){
			return response;
		}else{
			return null;
		}
	}
	
	/**
	 * 从消息实体中获取HTTP BODY内容
	 * @param entity
	 * @return StringBuffer
	 */
	private static StringBuffer getBodyOnEntity(HttpEntity entity,String encoding) {   
		if(encoding==null) encoding="UTF-8";
	    StringBuffer sb = new StringBuffer();
	    InputStreamReader isr = null;
	    BufferedReader br = null;
	    try {   
	        // 从消息实体中获取输入流对象   
	        InputStream inputStream = entity.getContent();
	        isr = new InputStreamReader(inputStream,encoding);
	        br = new BufferedReader(isr);
	        String line = null;   
	 
	        while ((line = br.readLine()) != null) {   
	        	sb.append(line + "\r\n");   
	        }   
	    } catch (Exception ex) {   
	        ex.printStackTrace();   
	    } finally {   
	        try {   
	        if(br!=null)br.close();
	        if(isr!=null)isr.close();
	        } catch (IOException e) {   
	        e.printStackTrace();   
	        }   
	    }   
	    return sb;   
	 }
	
	/**
	 * 调用远程创建方法
	 * @param url
	 * @return
	 */
	public JSONObject invokeRemateCreateService(String url,String param,String value){
		long startTime = System.currentTimeMillis();
		HttpResponse response = null;
    	HttpEntity entity = null;
    	StringBuffer body = null; 
    	
		DefaultHttpClient client = createHttpClient();
		HttpPost post = new HttpPost(url);
		List<NameValuePair> list  = new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair(param ,value));
		try {
			post.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
			response = client.execute(post);
			System.out.println("execute time:" + (System.currentTimeMillis()-startTime));
			response = parseRespnose(client,response);
			if(null!=response){
				entity = response.getEntity();
				body = getBodyOnEntity(entity,null);
	    		entity.consumeContent();
	    		System.out.println(body.toString());
	    		JSONObject json = JSON.parseObject(body.toString());
	    		System.out.println(json.getString("status"));
	    		System.out.println(json.getString("longurl"));
	    		System.out.println(json.getString("tinyurl"));
	    		System.out.println(json.getString("err_msg"));
	    		return json;
			}else{
    			return null;
    		}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	public static void main(String[] args){
		ShortUrlUtil util = new ShortUrlUtil();
		//util.createShortUrl("http://www.infoq.com/cn/articles/component-city");
		util.queryByShortUrl("http://dwz.cn/9RQw8");
	}
}
